import os
import sys
import cv2 as cv
import argparse


def parse_argv():
    parser = argparse.ArgumentParser(description='convert the format of all pictures in the directory')
    parser.add_argument('path', help='picture directory')
    parser.add_argument('src_format', help='before convertion format')
    parser.add_argument('dst_format', help='after convertion format')

    args = parser.parse_args()

    return args.path, args.src_format, args.dst_format


def convert(src, dst):
    img = cv.imread(src)
    cv.imwrite(dst, img)


def main():
    path, src_format, dst_format = parse_argv()
    names = os.listdir(path)
    for name in names:
        src_name = os.path.join(path, name)
        if not os.path.isfile(src_name) or name.split('.')[-1].lower() != src_format.lower():
            continue
        file_name = '.'.join(name.split('.')[:-1]) + '.' + dst_format.lower()
        dst_name = os.path.join(path, file_name)
        convert(src_name, dst_name)


if __name__ == '__main__':
    main()
